package com.why.whypaydemo.controller;

import com.why.whypaydemo.bean.PayParam;
import com.why.whypaydemo.service.AlipayServiceImpl;
import com.why.whypaydemo.util.Result;
import com.why.whypaydemo.util.ResultMap;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 *  支付宝支付，控制器
 *
 * @author wangziyang
 * */
@RestController
@RequestMapping(value = "/pay")
@AllArgsConstructor
public class PayController {


    @Autowired
    private AlipayServiceImpl alipayService;


    /**
     * 创建订单
     */
//    @ApiOperation(value = "创建订单", notes = "支付宝支付创建订单")
    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody PayParam payParam) {
        try {
            // 1、验证订单是否存在

            // 2、创建支付宝订单
            Result result = alipayService.createOrder(payParam);
            return result;
        } catch (Exception e) {

            return Result.fail();
        }
    }

    /**
     * 支付异步通知
     * 接收到异步通知并验签通过后，一定要检查通知内容，
     * 包括通知中的app_id、out_trade_no、total_amount是否与请求中的一致，并根据trade_status进行后续业务处理。
     * https://docs.open.alipay.com/194/103296
     */
    @RequestMapping("/notify")
    public String notify(HttpServletRequest request) {
        // 验证签名
        boolean flag = alipayService.rsaCheckV1(request);
        if (flag) {
            String tradeStatus = request.getParameter("trade_status"); // 交易状态
            String outTradeNo = request.getParameter("out_trade_no"); // 商户订单号
            String tradeNo = request.getParameter("trade_no"); // 支付宝订单号
            /**
             * 还可以从request中获取更多有用的参数，自己尝试
             */
            boolean notify = alipayService.notify(tradeStatus, outTradeNo, tradeNo);
            if(notify){
                return "success";
            }
        }
        return "fail";
    }

//    @ApiOperation(value = "退款", notes = "退款")
    @PostMapping("/refund")
    public ResultMap refund( @RequestParam String orderNo,
                            @RequestParam double amount,
                             @RequestParam(required = false) String refundReason) {
        return alipayService.refund(orderNo, amount, refundReason);
    }

    @GetMapping("/123")
    public String refund( ) {
        return "123";
    }





}
